package com.eliansun.util;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpClient {

    private static Logger LOG = LoggerFactory.getLogger(HttpClient.class);

    private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");

    private static OkHttpClient.Builder builder = null;

    static {
        builder = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS);

    }

    /**
     * 普通get请求
     *
     * @param url
     * @return
     */
    public static String get(String url, Map<String, String> headers) {
        Request request = new Request.Builder()
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
                .header("User-Agent", headers.get("user-agent"))
                .url(url)
                .get()
                .build();
        try {
            Response response = builder.build().newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (IOException e) {
            LOG.error("get[" + url + "]失败：" + e.getMessage());
        }
        return null;
    }


    /**
     * 请求头只带regerer的get
     * @param url
     * @param referer
     * @return
     */
    public static String getByReferer(String url, String referer) {
        Request request = new Request.Builder()
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
                .header("Referer", referer)
                .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML," +
                        " like Gecko) Chrome/68.0.3440.75 Safari/537.36")
                .url(url)
                .get()
                .build();
        try {
            Response response = builder.build().newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (IOException e) {
            LOG.error("get[" + url + "]失败：" + e.getMessage());
        }
        return null;
    }

}
